package scfg.utils;

import java.io.File;
import java.util.LinkedList;
import java.util.Queue;

import scfg.output.Display;
import scfg.output.RNAFormattedFile;

public class CtSequenceExtractor {

	public static String processFile(String filename, String outputName) {
		if (filename != null && outputName != null)
			return processFile(new File(filename), new File(outputName));
		if (filename != null)
			return processFile(new File(filename));
		// TODO:
		return null;
	}
	
	public static String processFile(File f) {
		return processFile(f, null);
	}
	
	public static String processFile(File f, File outputFile) {
		if (f == null || !f.exists() || !f.isFile()){
			// TODO: 
//			System.err.println("ARGS: " + f.getAbsolutePath());
			return null;
		} else if (!f.getName().contains(".nopct") && !f.getName().contains(".ct")) {
			// TODO: 
//			if(!f.getName().contains(".cnstr"))
//				System.err.println("NAME: " + f.getAbsolutePath());
			return null;
		}
		RNAFormattedFile rnaff = StructureAggregator.convertCtFile(f, new RNAFormattedFile());
		if (rnaff != null && rnaff.get("seq") != null) {
			if (outputFile != null) {
				File outputDir = new File(outputFile.getAbsolutePath().replace(outputFile.getName(), ""));
				outputDir.mkdirs();
				String constraintFileName = outputFile.getAbsolutePath().replace(".nopct", ".seq");
				Display fileout = new Display(constraintFileName, null, false);
				fileout.out(rnaff.get("seq"));
				fileout.finalizeDisplay();
			}
			return rnaff.get("seq");
		} // else
//			System.err.println("NULL: " + f.getAbsolutePath());
		return null;
	}
	
	public static void processDir(String filename, String destination) {
		processDir(new File(filename), destination);
	}
	
	public static void processDir(File base, String destination) {
		if (base == null || !base.exists() || !base.isDirectory()){
			// TODO:
			return;
		}
		File[] files = base.listFiles();
		Queue<File> dirs = new LinkedList<File>();
		for (File f : files) {
			if (f.isDirectory())
				dirs.offer(f);
			else
				processFile(f, new File(destination + "/" + f.getName()));
		}
		while (!dirs.isEmpty()) {
			File f = dirs.poll();
			processDir(f, destination + "/" + f.getName());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filename = "/home/david/Documents/RNA/ct_files/";
		String destination = "/home/david/Documents/RNA/ct_files/sequences/";
		processDir(filename, destination);
	}

}
